package com.yanqu.road.server.manger.activity.xiuxian;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.xiuxian.config.XiuXianConfig;
import com.yanqu.road.entity.activity.xiuxian.config.XiuXianPeakConfig;
import com.yanqu.road.entity.activity.xiuxian.data.XiuXianUserMountAllotData;
import com.yanqu.road.entity.activity.xiuxian.data.XiuXianUserMountInfoData;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.logic.bussiness.activity.XiuXianActivityBusiness;
import com.yanqu.road.pb.activity.XiuXianProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.xiuxian.XiuXianModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.math.BigInteger;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class XiuXianMgr extends TempMgr {

    private static XiuXianConfig config = null;

    private static RandomHelper randomHelper = new RandomHelper();
    // 宗门使用的体力
    private static long sectTotalEnergy = 0;
    // 玩家分配灵峰
    private static Map<Long, XiuXianUserMountAllotData> userMountAllotMap = new ConcurrentHashMap<>();

    /**
     * 重新加载活动
     */
    public static void reloadActivityData() {
        getLogger().info("reload XiuXianActivity start");
        List<ActivityInfo> list = NormalActivityMgr.getOpenActivityInfoList(eActivityType.XiuXian.getValue());
        if (list.isEmpty()) {
            config = null;
            userMountAllotMap.clear();
            sectTotalEnergy = 0;
            getLogger().info("reload XiuXianActivity end, no activity in show time.");
            return;
        }
        ActivityInfo activityInfo = list.get(0);

        loadConfigFromDb(activityInfo);
        getLogger().info("reload XiuXianActivity end, activityId {}.", config.getActivityInfo().getActivityId());

        // 加载用户灵峰数据
        userMountAllotMap = XiuXianActivityBusiness.getXiuXianUserMountAllotData(config.getActivityInfo().getActivityId());
        // 重置
        sectTotalEnergy = 0;

        for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
            player.getModule(XiuXianModule.class).xiuXianLogin();
        }
    }

    public static void offLine(GamePlayer player) {
        ActivityInfo activityInfo = getActivityInfo();
        if (activityInfo == null) {
            return;
        }
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            return;
        }
        // 离线通知跨服
        XiuXianProto.CrossXiuXianLeavePlaceReqMsg.Builder reqMsg = XiuXianProto.CrossXiuXianLeavePlaceReqMsg.newBuilder();
        reqMsg.setActivityId(activityInfo.getActivityId());
        player.sendPacket(CrossProtocol.C_CROSS_XIU_XIAN_OFF_LINE, reqMsg);
    }

    /**
     * 数据库加载配置
     */
    private static void loadConfigFromDb(ActivityInfo activityInfo) {
        // TODO
        Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(activityInfo.getActivityId());
        XiuXianConfig tmpConfig = new XiuXianConfig();
        tmpConfig.setActivityInfo(activityInfo);
        tmpConfig.setPlaceConfigMap(XiuXianActivityBusiness.getXiuXianPvpPlaceConfigMap(activityInfo.getActivityId()));
        // 初始化配置
        tmpConfig.initConfig(activityConfigMap);
        tmpConfig.setEquipmentConfigMap(XiuXianActivityBusiness.getXiuXianEquipmentConfigMap(activityInfo.getActivityId()));
        tmpConfig.setEventConfigMap(XiuXianActivityBusiness.getXiuXianEventConfigMap(activityInfo.getActivityId()));
        tmpConfig.setMissionConfigMap(XiuXianActivityBusiness.getXiuXianMissionMap(activityInfo.getActivityId()));
        tmpConfig.setStateConfigMap(XiuXianActivityBusiness.getXiuXianStateConfigMap(activityInfo.getActivityId()));
        tmpConfig.setTripodConfigMap(XiuXianActivityBusiness.getXiuXianTripodConfigMap(activityInfo.getActivityId()));
        tmpConfig.setNpcConfigMap(XiuXianActivityBusiness.getXiuXianNpcConfigMap(activityInfo.getActivityId()));
        tmpConfig.setUpgradeConfigMap(XiuXianActivityBusiness.getXiuXianUpgradeConfigMap(activityInfo.getActivityId()));
        tmpConfig.setPeakConfigMap(XiuXianActivityBusiness.getXiuXianPeakConfigMap(activityInfo.getActivityId()));
        config = tmpConfig;

    }

    public static XiuXianConfig getConfig() {
        return config;
    }

    /**
     * 活动信息
     */
    public static ActivityInfo getActivityInfo() {
        return config == null ? null : config.getActivityInfo();
    }

    public static long getSectTotalEnergy() {
        return sectTotalEnergy;
    }

    public static void setSectTotalEnergy(long sectTotalEnergy) {
        XiuXianMgr.sectTotalEnergy = sectTotalEnergy;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    /**
     * 获取并初始化用户灵峰分配数据
     */
    public static XiuXianUserMountAllotData getUserMountData(long userId) {
        if (userId == 0) {
            return null;
        }
        // 不存在则初始化
        if (!userMountAllotMap.containsKey(userId)) {
            synchronized (userMountAllotMap) {
                if (!userMountAllotMap.containsKey(userId)) {
                    XiuXianUserMountAllotData userMountAllotData = new XiuXianUserMountAllotData();
                    userMountAllotData.setActivityId(getActivityInfo().getActivityId());
                    userMountAllotData.setUserId(userId);
                    Map<Long, XiuXianUserMountInfoData> userMountMap = new ConcurrentHashMap<>();
                    XiuXianUserMountInfoData userMountInfoData = new XiuXianUserMountInfoData();
                    userMountInfoData.setMountId(getDefaultMount());
                    userMountMap.put(getHistoryAllotTime(System.currentTimeMillis()/1000), userMountInfoData);
                    userMountAllotData.setUserMountMap(userMountMap);
                    userMountAllotData.setInsertOption();
                    userMountAllotMap.put(userId, userMountAllotData);
                }
            }
        }
        return userMountAllotMap.get(userId);
    }

    @Override
    public boolean save() {
        if (userMountAllotMap != null) {
            for (XiuXianUserMountAllotData userMountAllotData : userMountAllotMap.values()) {
                if (userMountAllotData.isInsertOption()) {
                    XiuXianActivityBusiness.addXiuXianUserMountAllotData(userMountAllotData);
                } else if (userMountAllotData.isUpdateOption()) {
                    XiuXianActivityBusiness.updateXiuXianUserMountAllotData(userMountAllotData);
                }
            }
        }
        return true;
    }

    /**
     * 请求同步宗门体力
     */
    public static void reqSyncCampEnergy() {
        ActivityInfo activityInfo = getActivityInfo();
        if (activityInfo == null) {
            return;
        }
        // 活动期和领奖期才去同步
        if (!ActivityMgr.activityInTimeAndShowTime(activityInfo)) {
            return;
        }
        XiuXianProto.CrossXiuXianSyncCampEnergyReqMsg.Builder reqMsg = XiuXianProto.CrossXiuXianSyncCampEnergyReqMsg.newBuilder();
        reqMsg.setActivityId(activityInfo.getActivityId());
        GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_XIU_XIAN_SYNC_CAMP_ENERGY, reqMsg));
    }

    public static void syncSectEnergy(XiuXianProto.CrossXiuXianSyncCampEnergyRespMsg reqMsg) {
        // TODO 有变化成更新
        if (reqMsg.getCampTotalEnergy() != getSectTotalEnergy()) {
            // 更新内存
            setSectTotalEnergy(reqMsg.getCampTotalEnergy());
            // 更新在线玩家
            for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
                // 凡人修仙传使用药草总数量
                player.notifyListener(eGamePlayerEventType.XiuXianSectUseEnergyCount.getValue(), BigInteger.valueOf(getSectTotalEnergy()));
            }
        }
    }
    /**
     * 获取默认的灵峰id
     */
    public static int getDefaultMount() {
        XiuXianConfig config = XiuXianMgr.getConfig();
        for (XiuXianPeakConfig peakConfig : config.getPeakConfigMap().values()) {
            if(peakConfig.getRoomNum() == -1) {
                return peakConfig.getId();
            }
        }
        return 0;
    }
    /**
     * 获取分配时间
     */
    public static long getHistoryAllotTime(long historyTime) {
        int allotCount = (int)Math.floor((double)(historyTime - config.getActivityInfo().getBeginTime()) / config.getXIUXIAN_PEAK_ASSIGN_CD());
        // 当前的
        long tempAllotTimeId = config.getActivityInfo().getBeginTime() + allotCount * config.getXIUXIAN_PEAK_ASSIGN_CD();
        if (tempAllotTimeId < config.getActivityInfo().getBeginTime()) {
            tempAllotTimeId = config.getActivityInfo().getBeginTime();
        }
        return tempAllotTimeId;
    }
    /**
     * 同步灵峰分配
     * */
    public static void syncMountAllot(XiuXianProto.CrossXiuXianSyncAllotMountMsg reqMsg) {
        // 确认收到
        ActivityInfo activityInfo = getActivityInfo();
        if (activityInfo == null || activityInfo.getActivityId() != reqMsg.getActivityId()) {
            return;
        }
        long allotTime = reqMsg.getCurAllotTime();
        synchronized (userMountAllotMap) {
            // 更新数据
            Set<Long> hasMountUserIdSet = new HashSet<>();
            for (XiuXianProto.XiuXianUserMountAllotInfoTemp allotInfoTemp : reqMsg.getUserAllotListList()) {
                long userId = allotInfoTemp.getUserId();
                int mountId = allotInfoTemp.getMountId();
                XiuXianUserMountAllotData userMountAllotData = getUserMountData(userId);
                if (userMountAllotData == null) {
                    continue;
                }
                hasMountUserIdSet.add(userId);
                Map<Long, XiuXianUserMountInfoData> userMountInfoDataMap = userMountAllotData.getUserMountMap();
                XiuXianUserMountInfoData userMountInfoData = new XiuXianUserMountInfoData(mountId);
                userMountInfoDataMap.put(allotTime, userMountInfoData);
                userMountAllotData.setUserMountMap(userMountInfoDataMap);
            }
            // 更新没有灵峰的玩家
            int defaultMountId = getDefaultMount();
            for (XiuXianUserMountAllotData userMountAllotData : userMountAllotMap.values()) {
                if (hasMountUserIdSet.contains(userMountAllotData.getUserId())) {
                    continue;
                }
                Map<Long, XiuXianUserMountInfoData> userMountInfoDataMap = userMountAllotData.getUserMountMap();
                XiuXianUserMountInfoData userMountInfoData = new XiuXianUserMountInfoData(defaultMountId);
                userMountInfoDataMap.put(allotTime, userMountInfoData);
                userMountAllotData.setUserMountMap(userMountInfoDataMap);
            }

            XiuXianProto.CrossXiuXianAckAllotMountMsg.Builder builder = XiuXianProto.CrossXiuXianAckAllotMountMsg.newBuilder();
            builder.setCurAllotTime(allotTime);
            builder.setActivityId(activityInfo.getActivityId());
            GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_XIU_XIAN_ACK_CAMP_ENERGY, builder));
        }
    }
}
